import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import { Table, Tooltip, Divider, Popconfirm, Carousel } from 'antd';
import ScModalCore from '../../feedback/scModalCore';
import classNames from 'classnames';
import '../../../assets/stylus/com/display/grid.styl';
import fetchHandler from "../../../fetch/fetchHandler";
import {initGrids, initModals} from "../../../state/action/comAction";

class gridTable extends PureComponent {

  static contextTypes = {
    store: PropTypes.object.isRequired
  }

  constructor (props) {
    super(props);
    this.props = props;
    this.empty = {'emptyText': '暂无数据'};
    this.actionWrap = [];
    this.params = {
      page: 1,
      pagecount: this.props.config.tableParam.pageCount || 10 // pagecount默认请求每页数量
    };
    this.state = {
      loading: !1,
      gridData: null,
      pagination: {
        current: 1,
        total: 0,
        pageSize: this.props.config.tableParam.pageCount || 10,
        onShowSizeChange: (current) => {
          this.turnPage(current)
        },
        onChange:(current) => {
          this.turnPage(current)
        }
      }
    };
    // 设置checkbox选择参数，根据需要设置
    this.rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.params['ids'] = selectedRowKeys;
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
  }

  resolveColumns (columns) {
    let finalCols = [];
    columns.forEach((c, index) => {
      switch (c.colType) {
        case 'textCol':
          finalCols.push(Object.assign({
            title: c.name,
            dataIndex: c.key,
            key: c.key
          }, c.fix && {
            fixed: c.fix,
            width: 200
          }));
          break;
        case 'tipCol':
          finalCols.push(Object.assign({
            title: c.name,
            dataIndex: c.key,
            key: c.key,
            className: 'column-nowrap',
            render: this.showMoreTip
          }, c.fix && {
            fixed: c.fix
          }));
          break;
        case 'thumbImage':
          finalCols.push(Object.assign({
            title: c.name,
            dataIndex: c.key,
            key: c.key,
            render: this.generateThumbImageAction()
          }, c.fix && {
            fixed: c.fix
          }));
          break;
        case 'action':
          finalCols.push(Object.assign({
            title: c.name,
            key: c.key,
            render: this.generateActionWrap(c.actionMap)
          }, c.fix && {
            fixed: c.fix
          }));
          break;
        default:
          finalCols.push({
            title: c.name,
            dataIndex: c.key,
            key: c.key
          });
      }
    });
    return finalCols;
  }

  componentWillMount () {
    this.fetchData(!0, this.params);
    // 更新注入grid相关信息状态
    this.context.store.dispatch(initGrids(this.params, this.fetchData, this));
  }

  // 设置pop浮窗显示
  showMoreTip (text) {
    return (<Tooltip placement="topLeft" title={text} >
      {text}
    </Tooltip>);
  }

  // 构建图片预览交互

  generateThumbImageAction () {
    return (
      (text, record) =>
      <img onClick={() => this.openThumbModal(record.fullURL && record.fullURL.toString(), 0)} src={record.fullURL && record.fullURL.toString().split(',')[0]}/>
    )
  }

  openThumbModal (urls) {
    // 预栏的实现请参考模态窗口组件
    const thumbDom = [];
    for (let i of urls.split(',')) {
      i.length && thumbDom.push(<div key={i}><h3><img src={i} /></h3></div>);
    }
    this.content = (
      <div>
        <Carousel autoplay>
          {thumbDom}
        </Carousel>
      </div>
    );
    this.setState({
      modalConfig: {
        key: 'thumbModal',
        width: 600, // 自定义模态框宽度
        title: '预览图片', // 模态窗口的标题
        content: this.content, // 自定义 jsx内容
      }
    }, () => {
      this.context.store.dispatch(initModals(this.state.modalConfig.key, !0));
    });
  }

  // 构建action wrap
  generateActionWrap (actions) {
    const gridData = this.state.gridData;
    return (text, record) => (
      <div className="action-wrap">
        {
          actions.map(function (item, index) {
              const res = record;
              if (item.type === 'href') {
                return <span key={index + 'actionWrap'}>
                  <a href="javascript:void(0)" key={index + 'href'} onClick={() => {item.handler(res)}}>{item.actionName}</a>
                  {(index + 1) !== actions.length && <Divider type="vertical" />}
                </span>;
              }
              if (item.type === 'confirm') {
                return <span key={index + 'actionWrap'}>
                <Popconfirm  key={index + 'confirm'} title={'确认要' + item.actionName + '么?'} onConfirm={() => {item.handler(res)}}
                                   okText="确认" cancelText="取消">
                  <a href="javascript:void(0);" key={index + 'confirm-href'}>{item.actionName}</a>
                </Popconfirm>
                  {(index + 1) !== actions.length && <Divider type="vertical" />}
                </span>;
              }
            }
            )
        }
        </div>
    );
  }

  // 获取列表数据
  fetchData (isInit, params) {
    // 判断是否需要重置页码
    isInit && (this.state.pagination.current = 1, params.page = 1);
    this.beginLoading();
    return fetchHandler(this.props.config.dataApi, params).then((res) => {
      this.endLoading(res);
      return res;
    });
  }

  // 跳转页码
  turnPage (current) {
    this.params['page'] = parseInt(current);
    this.state.pagination.current = parseInt(current);
    this.fetchData(!1, this.params);
  }

  // 开始loading
  beginLoading () {
    this.setState({
      loading: !0
    });
  }

  // 结束loading
  endLoading (res) {
    res.data && (this.state.pagination.total = res.pageLimit.totalCount);
    this.setState({
      loading: !1,
      gridData: res.data ? res.data : null,
      pagination: this.state.pagination
    });
  }

  render () {
    const className = classNames({
      'sc-table': !0,
      'table-center': this.props.postyle || 'table-center'
    });
    return <div>
      <Table
        className={className}
        dataSource={this.state.gridData && JSON.parse(JSON.stringify(this.state.gridData).replace(/id/g,'key').replace(/null/g,'"---"'))}
        columns={this.resolveColumns(this.props.config.tableColumns)}
        locale={this.empty}
        pagination = {this.state.pagination}
        loading={this.state.loading}
        scroll={{x: '100%'}}
        onChange={this.props.config.tableChange}
        rowSelection={this.props.config.tableInfo.hasRow ? this.rowSelection : null}
      />
      {this.state.modalConfig && <ScModalCore config={this.state.modalConfig}></ScModalCore>}
    </div>
  }
}

export default gridTable;

gridTable.propTypes = {
  config: PropTypes.object,
}